#!/bin/bash

# ============================================================
# OHOS HTTP 测试服务器 - 启动脚本
# 用途：启动 HTTP 测试服务器（包含证书生成）
# 使用: ./startServer.sh [IP地址]
# 示例: ./startServer.sh 47.107.58.65
# ============================================================

set -e

SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
cd "$SCRIPT_DIR"

# 颜色定义
RESET='\033[0m'
GREEN='\033[32m'
YELLOW='\033[33m'
CYAN='\033[36m'
BOLD='\033[1m'

echo -e "${CYAN}============================================${RESET}"
echo -e "${CYAN}  OHOS HTTP 测试服务器 - 启动${RESET}"
echo -e "${CYAN}============================================${RESET}"
echo ""

# 获取服务器IP
SERVER_IP=""
if [ -n "$1" ]; then
    SERVER_IP="$1"
    echo -e "${CYAN}📍 使用指定的服务器IP: ${GREEN}${SERVER_IP}${RESET}"
else
    echo -e "${CYAN}📍 检测服务器IP...${RESET}"
    PUBLIC_IP=""
    if command -v curl &> /dev/null; then
        PUBLIC_IP=$(curl -s --connect-timeout 3 --max-time 5 ifconfig.me 2>/dev/null || \
                    curl -s --connect-timeout 3 --max-time 5 icanhazip.com 2>/dev/null || echo "")
    fi
    
    if [ -z "$PUBLIC_IP" ]; then
        PUBLIC_IP=$(hostname -I 2>/dev/null | awk '{print $1}')
        [ -z "$PUBLIC_IP" ] && PUBLIC_IP="127.0.0.1"
        echo -e "   ${YELLOW}使用本地IP: ${PUBLIC_IP}${RESET}"
    else
        echo -e "   ${GREEN}检测到公网IP: ${PUBLIC_IP}${RESET}"
    fi
    SERVER_IP="$PUBLIC_IP"
fi
echo ""

# 创建必要目录
echo -e "${CYAN}📁 创建目录结构...${RESET}"
mkdir -p logs pids cert upload public
echo -e "${GREEN}✅ 目录创建完成${RESET}"
echo ""

# 生成证书
echo -e "${CYAN}📝 生成/检查证书 (服务器IP: ${SERVER_IP})...${RESET}"
cd cert

if [ ! -f "server.crt" ]; then
    echo -e "   ${CYAN}生成新证书...${RESET}"
    
    # 构建 SAN 扩展
    SAN_EXT="DNS:localhost,DNS:*.local,DNS:*.65,IP:127.0.0.1,IP:0.0.0.0"
    if [ "$SERVER_IP" != "localhost" ] && [ "$SERVER_IP" != "127.0.0.1" ]; then
        SAN_EXT="${SAN_EXT},IP:${SERVER_IP}"
    fi
    
    # 1. 生成服务器证书（HTTPS 单向认证 - 端口 4001）
    openssl req -x509 -newkey rsa:2048 -nodes \
        -keyout server.key -out server.crt -days 365 \
        -subj "/C=CN/ST=Beijing/L=Beijing/O=OHOS Test/CN=${SERVER_IP}" \
        -addext "subjectAltName=${SAN_EXT}" 2>/dev/null
    echo -e "   ${GREEN}✅ 服务器证书生成完成 (server.crt, server.key)${RESET}"
    
    # 2. 创建 CA 证书（用于签发客户端证书）
    cp server.crt ca.crt
    cp server.key ca.key
    echo -e "   ${GREEN}✅ CA证书创建完成 (ca.crt, ca.key)${RESET}"
    
    # 3. 生成客户端证书（无密码 - 用于端口 4003）
    openssl req -newkey rsa:2048 -nodes \
        -keyout client.key -out client.csr \
        -subj "/C=CN/ST=Beijing/L=Beijing/O=OHOS Client/CN=client" 2>/dev/null
    
    openssl x509 -req -in client.csr \
        -CA ca.crt -CAkey ca.key \
        -CAcreateserial -out client.crt -days 365 2>/dev/null
    echo -e "   ${GREEN}✅ 客户端证书生成完成 (client.crt, client.key - 无密码)${RESET}"
    
    # 4. 生成加密版本的客户端私钥（用于端口 4002）
    openssl rsa -des3 -in client.key -out client_encrypted.key -passout pass:123456 2>/dev/null
    echo -e "   ${GREEN}✅ 加密客户端私钥生成完成 (client_encrypted.key - 密码: 123456)${RESET}"
    
    # 5. 生成 P12 证书包（无密码）
    openssl pkcs12 -export -out client.p12 \
        -inkey client.key -in client.crt -certfile ca.crt \
        -passout pass: 2>/dev/null
    echo -e "   ${GREEN}✅ P12证书包生成完成 (client.p12 - 无密码)${RESET}"
    
    # 6. 生成 P12 证书包（带密码）
    openssl pkcs12 -export -out client_encrypted.p12 \
        -inkey client_encrypted.key -passin pass:123456 \
        -in client.crt -certfile ca.crt \
        -passout pass:123456 2>/dev/null
    echo -e "   ${GREEN}✅ 加密P12证书包生成完成 (client_encrypted.p12 - 密码: 123456)${RESET}"
    
    # 清理临时文件
    rm -f client.csr ca.srl
    
    echo ""
    echo -e "${GREEN}✅ 所有证书生成完成${RESET}"
    echo -e "${CYAN}   证书说明:${RESET}"
    echo -e "   - 端口 4001 (HTTPS 单向): 使用 server.crt + server.key"
    echo -e "   - 端口 4002 (双向+密码): 使用 ca.crt + client_encrypted.key (密码: 123456)"
    echo -e "   - 端口 4003 (双向无密码): 使用 ca.crt + client.key"
else
    echo -e "${GREEN}✅ 证书已存在，跳过生成${RESET}"
fi

cd ..
echo ""

# 安装依赖
echo -e "${CYAN}📦 检查依赖...${RESET}"
if [ -f "package.json" ]; then
    if [ ! -d "node_modules" ]; then
        echo -e "   ${CYAN}安装 npm 依赖...${RESET}"
        npm install
        echo -e "${GREEN}✅ 依赖安装完成${RESET}"
    else
        echo -e "${GREEN}✅ 依赖已安装${RESET}"
    fi
else
    echo -e "${YELLOW}⚠️  未找到 package.json${RESET}"
fi
echo ""

# 停止旧进程
if [ -f "pids/server.pid" ]; then
    OLD_PID=$(cat pids/server.pid)
    if ps -p $OLD_PID > /dev/null 2>&1; then
        echo -e "${YELLOW}⚠️  发现运行中的服务器 (PID: $OLD_PID)，正在停止...${RESET}"
        kill $OLD_PID 2>/dev/null || true
        sleep 2
        echo -e "${GREEN}✅ 旧服务器已停止${RESET}"
    fi
fi
echo ""

# 启动服务器
echo -e "${CYAN}🚀 启动 HTTP 测试服务器...${RESET}"

if [ -f "server.js" ]; then
    node server.js > logs/server.log 2>&1 &
    SERVER_PID=$!
    echo $SERVER_PID > pids/server.pid
else
    echo -e "${YELLOW}❌ 未找到 server.js${RESET}"
    exit 1
fi

sleep 2

# 验证服务器是否启动
if ps -p $SERVER_PID > /dev/null 2>&1; then
    echo -e "${GREEN}✅ 服务器启动成功 (PID: $SERVER_PID)${RESET}"
else
    echo -e "${YELLOW}❌ 服务器启动失败，请检查日志${RESET}"
    cat logs/server.log 2>/dev/null || true
    exit 1
fi

echo ""
echo -e "${CYAN}============================================${RESET}"
echo -e "${GREEN}${BOLD}  ✅ 服务器已启动${RESET}"
echo -e "${CYAN}============================================${RESET}"
echo ""
echo -e "${CYAN}📋 服务访问信息:${RESET}"
echo -e "   ${GREEN}HTTP:${RESET}       http://${SERVER_IP}:4000"
echo -e "   ${GREEN}HTTPS 单向:${RESET}  https://${SERVER_IP}:4001"
echo -e "   ${GREEN}HTTPS 双向+密码:${RESET} https://${SERVER_IP}:4002 ${YELLOW}(密码: 123456)${RESET}"
echo -e "   ${GREEN}HTTPS 双向无密码:${RESET} https://${SERVER_IP}:4003"
echo -e "   ${GREEN}API 文档:${RESET}   http://${SERVER_IP}:4000/api-docs"
echo ""
echo -e "${CYAN}🔌 代理服务器:${RESET}"
echo -e "   ${GREEN}SOCKS5 代理:${RESET}     ${SERVER_IP}:1080 ${YELLOW}(需认证: socks5user/socks5pass)${RESET}"
echo -e "   ${GREEN}HTTP/HTTPS 代理:${RESET} ${SERVER_IP}:8080 ${YELLOW}(无认证)${RESET}"
echo -e "   ${GREEN}HTTP/HTTPS 代理:${RESET} ${SERVER_IP}:8081 ${YELLOW}(需认证: admin/123456)${RESET}"
echo ""
echo -e "${CYAN}📋 管理命令:${RESET}"
echo -e "   ${YELLOW}查看日志:${RESET} tail -f logs/server.log"
echo -e "   ${YELLOW}停止服务器:${RESET} kill \$(cat pids/server.pid)"
echo -e "   ${YELLOW}重启服务器:${RESET} kill \$(cat pids/server.pid) && ./startServer.sh"
echo ""
echo -e "${CYAN}📋 证书文件位置:${RESET}"
echo -e "   cert/ca.crt              - CA证书"
echo -e "   cert/server.crt          - 服务器证书"
echo -e "   cert/client.crt          - 客户端证书"
echo -e "   cert/client.key          - 客户端私钥 (无密码)"
echo -e "   cert/client_encrypted.key - 客户端私钥 (密码: 123456)"
echo ""